<script>
import { Search, ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import { StudioAPI } from "../apis";
import { useUserStore } from "../stores";
import { ElMessage } from "element-plus";
import DraggableUpload from "../components/DraggableUpload.vue";

import { ref } from "vue";
export default {
  setup() {
    const thumbnailRef = ref(null);
    return {
      thumbnailRef,
    };
  },
  data() {
    return {
      uploadFun: StudioAPI.draggableUpload,
      query: {
        page: 1,
        keywords: null,
        category_id: null,
        page_size: 20,
      },
      products: [],
      categories: [],
      has_more: false,
      editing_product: {
        product_id: null,
        name: "",
        price: 100,
        priority: 0,
        thumbnail_url: null,
        remark: "",
        category_id: null,
      },
    };
  },
  components: {
    DraggableUpload,
    Search,
    ArrowRight,
    ArrowLeft,
  },
  async mounted() {
    this.userStore = useUserStore();
    await this.getCategories();
    await this.switchCategory(this.categories[0].category_id);
  },
  methods: {
    async getCategories() {
      const categories = await StudioAPI.getCategories();
      this.categories = categories;
      this.query.category_id = categories[0].category_id;
    },
    async switchCategory(category_id) {
      this.query.category_id = category_id;
      this.query.page = 1;
      await this.getProducts();
    },
    async getProducts() {
      const products = await StudioAPI.getProducts(this.query);
      this.products = products;
      this.has_more = products.length === this.query.page_size;
    },

    async nextPage() {
      this.query.page += 1;
      await this.getProducts();
    },
    async prevPage() {
      this.query.page -= 1;
      await this.getProducts();
    },
    async searchProducts() {
      this.query.page = 1;
      await this.getProducts(this.query);
    },
    async confirmKeywords(page) {
      this.query.page = isNaN(page) ? 1 : page;
      await this.getProducts();
    },

    // 点击顾客行
    async clickProductRow(product) {
      const index = this.products.findIndex(
        (c) => c.product_id === product.product_id
      );
      if (index < 0) return;
      this.editing_product = Object.assign({}, product);

      this.thumbnailRef.images = [{ url: this.editing_product.thumbnail_url }];
    },

    async addProduct() {
      this.reset();
    },

    async confirmUpsert() {
      this.editing_product.thumbnail_url = this.thumbnailRef.images.map(
        (i) => i.response || i.url
      )[0];

      if (this.editing_product.product_id) {
        const {
          success,
          data: product,
          message,
        } = await StudioAPI.updateProduct({
          ...this.editing_product,
        });
        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!product.product_id) throw product;

        const index = this.products.findIndex(
          (p) => p.product_id === product.product_id
        );
        if (index > -1) {
          this.products[index] = product;
        }
      } else {
        const {
          success,
          data: product,
          message,
        } = await StudioAPI.createProduct({
          ...this.editing_product,
        });
        if (!success) {
          ElMessage.warning(message);
          return;
        }

        // 出错
        if (!product.product_id) throw product;
        this.products.splice(0, 0, product);
      }
      this.reset();
    },
    reset() {
      this.editing_product = {
        product_id: null,
        name: "",
        price: 100,
        thumbnail_url: null,
        remark: "",
        category_id: null,
      };

      this.thumbnailRef.images = [];
    },
  },
};
</script>
<template>
  <el-container>
    <el-main style="padding: 5px" width="auto">
      <div class="filter-header">
        <!-- 底部换页 -->
        <div style="display: flex; overflow: scroll">
          <div
            style="margin-right: 10px"
            v-for="category of categories"
            :key="category.category_id"
          >
            <el-button
              :type="
                category.category_id === query.category_id
                  ? 'primary'
                  : 'default'
              "
              @click="switchCategory(category.category_id)"
              >{{ category.name }}</el-button
            >
          </div>
        </div>
      </div>

      <div class="filter-header">
        <!-- 底部换页 -->
        <div style="display: flex">
          <el-input
            v-model="query.keywords"
            clearable
            placeholder="名字"
            size="large"
            @keyup.enter="confirmKeywords"
          >
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <div style="flex: 1; margin-left: 20px">
            <el-button
              @click="prevPage"
              :disabled="query.page === 1"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-left /></el-icon>
            </el-button>
          </div>
          <div style="flex: 1; margin-left: 5px">
            <el-button
              @click="nextPage"
              :disabled="!has_more"
              size="large"
              style="width: 100%"
            >
              <el-icon size="20"><arrow-right /></el-icon>
            </el-button>
          </div>
        </div>
        <div>
          <el-button @click="addProduct" size="large" style="width: 100%">
            添加商品
          </el-button>
        </div>
      </div>
      <el-table
        :data="products"
        highlight-current-row
        height="88vh"
        @row-click="clickProductRow"
        stripe
      >
        <el-table-column prop="category_name" label="类目" width="140" />
        <el-table-column prop="name" label="名字" width="140" />
        <el-table-column prop="priority" label="优先级" width="140" />
        <el-table-column prop="price" label="售价" width="140" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.thumbnail_url"
              fit="cover"
              :preview-src-list="[scope.row.thumbnail_url]"
              :preview-teleported="true"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 右侧表单 -->
    <el-aside style="padding: 5px; width: 400px">
      <el-card shadow="hover">
        <template #header>
          <div class="flex-between">
            <div style="font-size: var(--el-font-size-large)">增改产品</div>
            <div>
              <el-button type="primary" @click="confirmUpsert" size="large">
                保存
              </el-button>
            </div>
          </div>
        </template>
        <el-form :model="editing_product" label-width="80px">
          <el-form-item label="产品类目" prop="category_id">
            <el-radio-group
              v-model="editing_product.category_id"
              :disabled="editing_product.product_id !== null"
            >
              <el-radio
                v-for="category in categories"
                :key="category.category_id"
                :label="category.category_id"
                size="large"
                border
              >
                {{ category.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="名字" prop="name">
            <el-input v-model="editing_product.name" />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-input-number v-model="editing_product.priority" />
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input-number v-model="editing_product.price" :min="0" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editing_product.remark" />
          </el-form-item>

          <el-form-item label="预览图" prop="thumbnail_urls">
            <draggable-upload
              ref="thumbnailRef"
              :upload-fun="uploadFun"
              :multiple="false"
            ></draggable-upload>
          </el-form-item>
        </el-form>
      </el-card>
    </el-aside>
  </el-container>
</template>

<style scoped>
.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  row-gap: 10px;
  column-gap: 10px;
  grid-auto-rows: 240px;
  overflow: auto;
  height: calc(100vh - 70px);
}

.image-item {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 5px;
}

.el-table .el-table__cell {
  position: unset;
}
</style>
